package com.itany.nmms.controller;

import com.github.pagehelper.PageInfo;
import com.itany.nmms.entity.Dept;
import com.itany.nmms.entity.Product;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.service.DeptService;
import com.itany.nmms.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 * 登录
 */
@Controller
@RequestMapping("/staff")
public class StaffController {

    @Autowired
    private StaffService staffService;
    @Autowired
    private DeptService deptService;

    @RequestMapping("/login")
    public ModelAndView login(String loginName, String password, String role, String code, HttpSession session) {
        ModelAndView mav = new ModelAndView();
        // 获取图片中的验证码信息
        String image = (String) session.getAttribute("code");
        try {
            Staff staff = staffService.login(loginName, password, role, code, image);
            session.setAttribute("staff", staff);
            mav.setViewName("redirect:/showMain");
        } catch (RequestParameterErrorException e) {
            mav.addObject("staffMsg", e.getMessage());
            mav.setViewName("backend/login");
        } catch (CodeErrorException e) {
            mav.addObject("staffMsg", e.getMessage());
            mav.setViewName("backend/login");
        } catch (StaffNotExistException e) {
            mav.addObject("staffMsg", e.getMessage());
            mav.setViewName("backend/login");
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("staffMsg", "服务器内部异常");
            mav.setViewName("backend/login");
        }
        return mav;
    }

    @RequestMapping("/findByParams")
    public ModelAndView findByParams(Staff staffParam,String pageNo,String pageSize){
        ModelAndView mav=new ModelAndView();
        List<Dept> depts=deptService.findAll();
        mav.addObject("depts",depts);

        PageInfo<Staff> staffPage=staffService.findByParams(staffParam,pageNo,pageSize);
        mav.addObject("staffPage",staffPage);
        mav.setViewName("backend/staffManager");
//        讲条件参数再次传回前台
        mav.addObject("staffParam",staffParam);
        return mav;
    }
}